<?php

namespace App\Http\Middleware;

use App\Models\AdminRole;
use App\Models\Nav;
use App\Models\Role;
use App\Models\RoleNav;
use Closure;
use Illuminate\Support\Facades\Auth;

class AdminAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$guard = 'admin')
    {
        if(!Auth::guard($guard)->check()){
            if($request->ajax() || $request->wantsJson()){
                return response()->json([ 'code'=>'-1',  'msg'=>'登录认证失败！',  'data'=>[]]);
            }else{
                return redirect()->guest('/login');
            }
        }

        $url = '/'.$request->path();
        $role_id = AdminRole::where('admin_id',Auth::guard('admin')->user()->id)->value('role_id');
        $access = Role::where('id',$role_id)->value('access');

        $navs = Nav::whereIn('id',json_decode($access,true))->orderBy('sort','asc')->pluck('link')->toArray();

        if(!in_array($url,$navs)&&!in_array($url,['//','/home','/logout'])){
            return response()->json([ 'code'=>'-1',  'msg'=>'权限不足！',  'data'=>[]]);
        }

        return $next($request);
    }
}
